package com.ruoyi.reportsnhnt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.report_gc.domain.bo.GcjxljjtbgBsInfoBo;
import com.ruoyi.report_tg.domain.vo.TgsybgBaDetailVo;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.syrw.annotation.FIllBasicInfoForTaiZhang;
import com.ruoyi.syrw.common.LineFunction;
import com.ruoyi.syrw.common.LineUtil;
import com.ruoyi.report_tg.domain.vo.GeneralCharDataVo;
import com.ruoyi.reportsnhnt.domain.ReportSnhntPhbsjBaDetail;
import com.ruoyi.reportsnhnt.domain.ReportSnhntPhbsjsybgBaDetail;
import com.ruoyi.reportsnhnt.mapper.ReportSnhntPhbsjsybgBaDetailMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.reportsnhnt.domain.bo.ReportSnhntPhbbgBsInfoBo;
import com.ruoyi.reportsnhnt.domain.vo.ReportSnhntPhbbgBsInfoVo;
import com.ruoyi.reportsnhnt.domain.ReportSnhntPhbbgBsInfo;
import com.ruoyi.reportsnhnt.mapper.ReportSnhntPhbbgBsInfoMapper;
import com.ruoyi.reportsnhnt.service.IReportSnhntPhbbgBsInfoService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 普通混凝土配合比设计试验检测报告Service业务层处理
 *
 * @author zxs
 * @date 2024-08-12
 */
@RequiredArgsConstructor
@Service
public class ReportSnhntPhbbgBsInfoServiceImpl implements IReportSnhntPhbbgBsInfoService {

    private final ReportSnhntPhbbgBsInfoMapper baseMapper;
    private final ReportSnhntPhbsjsybgBaDetailMapper detailMapper;

    /**
     * 查询普通混凝土配合比设计试验检测报告
     */
    @Override
    @FIllBasicInfo
    public ReportSnhntPhbbgBsInfoVo queryById(Long excelId){
        ReportSnhntPhbbgBsInfoVo vo = baseMapper.selectVoById(excelId);
        LambdaQueryWrapper<ReportSnhntPhbsjsybgBaDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReportSnhntPhbsjsybgBaDetail::getExcelId,excelId);
        List<ReportSnhntPhbsjsybgBaDetail> detailList = detailMapper.selectList(wrapper);
        //查询记录表中子表数据；
        List<ReportSnhntPhbsjBaDetail> dataList = detailMapper.selectListByBgExcelId(excelId);
        if (CollUtil.isNotEmpty(detailList)) {
            vo.setDetailList(detailList);
        }
        if (CollUtil.isNotEmpty(dataList)) {
            vo.setDataList(dataList);
        }
        return compute(vo);
    }

    @Override
    @FIllBasicInfoForTaiZhang
    public ReportSnhntPhbbgBsInfoVo queryByIdForTaizhang(Long excelId) {
        ReportSnhntPhbbgBsInfoVo vo = baseMapper.selectVoById(excelId);
        LambdaQueryWrapper<ReportSnhntPhbsjsybgBaDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReportSnhntPhbsjsybgBaDetail::getExcelId,excelId);
        List<ReportSnhntPhbsjsybgBaDetail> detailList = detailMapper.selectList(wrapper);
        //查询记录表中子表数据；
        List<ReportSnhntPhbsjBaDetail> dataList = detailMapper.selectListByBgExcelId(excelId);
        vo.setDetailList(detailList);
        vo.setDataList(dataList);
        return compute(vo);
    }

    /**
     * 查询普通混凝土配合比设计试验检测报告列表
     */
    @Override
    public TableDataInfo<ReportSnhntPhbbgBsInfoVo> queryPageList(ReportSnhntPhbbgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ReportSnhntPhbbgBsInfo> lqw = buildQueryWrapper(bo);
        Page<ReportSnhntPhbbgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询普通混凝土配合比设计试验检测报告列表
     */
    @Override
    public List<ReportSnhntPhbbgBsInfoVo> queryList(ReportSnhntPhbbgBsInfoBo bo) {
        LambdaQueryWrapper<ReportSnhntPhbbgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ReportSnhntPhbbgBsInfo> buildQueryWrapper(ReportSnhntPhbbgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ReportSnhntPhbbgBsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPage() != null, ReportSnhntPhbbgBsInfo::getPage, bo.getPage());
        lqw.eq(bo.getTotalPage() != null, ReportSnhntPhbbgBsInfo::getTotalPage, bo.getTotalPage());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), ReportSnhntPhbbgBsInfo::getJiancdwmc, bo.getJiancdwmc());
        lqw.eq(StringUtils.isNotBlank(bo.getBaogbh()), ReportSnhntPhbbgBsInfo::getBaogbh, bo.getBaogbh());
        lqw.eq(StringUtils.isNotBlank(bo.getShigwtdw()), ReportSnhntPhbbgBsInfo::getShigwtdw, bo.getShigwtdw());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcmc()), ReportSnhntPhbbgBsInfo::getGongcmc, bo.getGongcmc());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), ReportSnhntPhbbgBsInfo::getGongcbwyt, bo.getGongcbwyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpxx()), ReportSnhntPhbbgBsInfo::getYangpxx, bo.getYangpxx());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), ReportSnhntPhbbgBsInfo::getJiancyj, bo.getJiancyj());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), ReportSnhntPhbbgBsInfo::getPandyj, bo.getPandyj());
        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), ReportSnhntPhbbgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
        lqw.eq(StringUtils.isNotBlank(bo.getWeitbh()), ReportSnhntPhbbgBsInfo::getWeitbh, bo.getWeitbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJianclb()), ReportSnhntPhbbgBsInfo::getJianclb, bo.getJianclb());
        lqw.eq(StringUtils.isNotBlank(bo.getHunntzl()), ReportSnhntPhbbgBsInfo::getHunntzl, bo.getHunntzl());
        lqw.eq(bo.getShiyrq() != null, ReportSnhntPhbbgBsInfo::getShiyrq, bo.getShiyrq());
        lqw.eq(StringUtils.isNotBlank(bo.getKangsdj()), ReportSnhntPhbbgBsInfo::getKangsdj, bo.getKangsdj());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancxm()), ReportSnhntPhbbgBsInfo::getJiancxm, bo.getJiancxm());
        lqw.eq(StringUtils.isNotBlank(bo.getJiszb()), ReportSnhntPhbbgBsInfo::getJiszb, bo.getJiszb());
        lqw.eq(StringUtils.isNotBlank(bo.getShebIds()), ReportSnhntPhbbgBsInfo::getShebIds, bo.getShebIds());
        lqw.eq(StringUtils.isNotBlank(bo.getBgFlag()), ReportSnhntPhbbgBsInfo::getBgFlag, bo.getBgFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), ReportSnhntPhbbgBsInfo::getFujsm, bo.getFujsm());
        lqw.eq(StringUtils.isNotBlank(bo.getJianc()), ReportSnhntPhbbgBsInfo::getJianc, bo.getJianc());
        lqw.eq(StringUtils.isNotBlank(bo.getJil()), ReportSnhntPhbbgBsInfo::getJil, bo.getJil());
        lqw.eq(StringUtils.isNotBlank(bo.getFuh()), ReportSnhntPhbbgBsInfo::getFuh, bo.getFuh());
        lqw.eq(bo.getRiq() != null, ReportSnhntPhbbgBsInfo::getRiq, bo.getRiq());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjg()), ReportSnhntPhbbgBsInfo::getJiancjg, bo.getJiancjg());
        lqw.eq(StringUtils.isNotBlank(bo.getJiegpd()), ReportSnhntPhbbgBsInfo::getJiegpd, bo.getJiegpd());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), ReportSnhntPhbbgBsInfo::getJiancjl, bo.getJiancjl());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyjIds()), ReportSnhntPhbbgBsInfo::getJiancyjIds, bo.getJiancyjIds());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyjIds()), ReportSnhntPhbbgBsInfo::getPandyjIds, bo.getPandyjIds());
        return lqw;
    }

    /**
     * 新增普通混凝土配合比设计试验检测报告
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(ReportSnhntPhbbgBsInfoBo bo) {
        ReportSnhntPhbbgBsInfo add = BeanUtil.toBean(bo, ReportSnhntPhbbgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            //插入子表，8条
            List<ReportSnhntPhbsjsybgBaDetail> detailList = new ArrayList<>();
            for(int i =0 ;i< 8;i++){
                ReportSnhntPhbsjsybgBaDetail detail = new ReportSnhntPhbsjsybgBaDetail();
                detail.setExcelId(bo.getExcelId());
                detailList.add(detail);
            }
            detailMapper.insertBatch(detailList);
        }
        return flag;
    }

    /**
     * 修改普通混凝土配合比设计试验检测报告
     */
    @Override
    @DSTransactional
    public Boolean updateByBo(ReportSnhntPhbbgBsInfoBo bo) {
        // 增加对 是否合格 的填充
        fillExcelResult(bo);
        ReportSnhntPhbbgBsInfo update = BeanUtil.toBean(bo, ReportSnhntPhbbgBsInfo.class);
        validEntityBeforeSave(update);
        //更新子表
        if(bo.getDetailList()!=null&& bo.getDetailList().size()!=0){
            detailMapper.updateBatchById(bo.getDetailList());
        }
        return baseMapper.updateById(update) > 0;
    }

    private void fillExcelResult(ReportSnhntPhbbgBsInfoBo bo) {
//        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
//            for (TgsybgBaDetailVo detailVo : bo.getBaDetailVos()) {
//                if ("不符合".equals(detailVo.getJiegpd())) {
//                    bo.setExcelResult(2);
//                    return;
//                }
//            }
//            bo.setExcelResult(1);
//        }
        bo.setExcelResult(1);
    }

    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ReportSnhntPhbbgBsInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除普通混凝土配合比设计试验检测报告
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ReportSnhntPhbbgBsInfoVo compute(ReportSnhntPhbbgBsInfoVo vo) {
// 1. 参数判断 如果有任何一个为空,则 直接原样返回
        List<ReportSnhntPhbsjBaDetail> detailVos = vo.getDataList();
        if (CollUtil.isEmpty(detailVos)) {
            return vo;
        }

        // 1.2 非空判断
        for (ReportSnhntPhbsjBaDetail detailVo : detailVos) {
            if (BigDecimalUtil.isAnyOneEmpty(detailVo.getEpjqdq1()) || StrUtil.isEmpty(detailVo.getShuijb())) {
                return vo;
            }
        }
        double[][] data = new double[detailVos.size()][2];
        for (int i = 0; i < detailVos.size(); i++) {
            BigDecimal jiaosb = BigDecimalUtil.divide(BigDecimal.valueOf(1),new BigDecimal(detailVos.get(i).getShuijb()));
            data[i][0] = jiaosb.doubleValue();
            data[i][1] = detailVos.get(i).getEpjqdq1().doubleValue();
        }
        // 2 计算
        LineFunction generalLine = LineUtil.getGeneralLine(data);
        // 3 画图的数据
        // 3.1 画图所需要的 data  参与画线 不展示 不突出辅助线
        BigDecimal jiaosb0 = BigDecimalUtil.divide(BigDecimal.valueOf(1),new BigDecimal(detailVos.get(0).getShuijb()));
        BigDecimal jiaosbl = BigDecimalUtil.divide(BigDecimal.valueOf(1),new BigDecimal(detailVos.get(detailVos.size()-1).getShuijb()));
        List<GeneralCharDataVo> charData = generateData(generalLine, jiaosb0.doubleValue(),jiaosbl.doubleValue());
        // 3.2 其他的点 不参与画线 展示 不突出辅助线
        for (double[] datum : data) {
            charData.add(new GeneralCharDataVo(datum, "010"));
        }
//        // 3.3 参与画线 展示 突出辅助线
//        charData.add(new GeneralCharDataVo(new double[]{vo.getZuijhsl().doubleValue(), vo.getZuidgmd().doubleValue()}, "011"));
        vo.setChartData(charData);
        // 4 函数式
        vo.setFangcs("y=" + BigDecimalUtil.defaultValue(generalLine.getK(), 3)
            + "x+" + BigDecimalUtil.defaultValue(generalLine.getB(), 3));

        return vo;
    }




    private List<GeneralCharDataVo> generateData(LineFunction generalLine, double start, double end) {
        List<GeneralCharDataVo> result = new ArrayList<>(20);
        result.add(new GeneralCharDataVo(new double[]{BigDecimalUtil.defaultValue(start,2).doubleValue(), generalLine.getY(start)}, "100"));
        result.add(new GeneralCharDataVo(new double[]{BigDecimalUtil.defaultValue(end,2).doubleValue(), generalLine.getY(end)}, "100"));
        return result;
    }
}
